<script setup>
import { ref, reactive, onMounted, computed, nextTick, watch } from "vue";
import { ElMessage, ElMessageBox } from "element-plus";
import {
  Plus,
  Search,
  Edit,
  View,
  Delete,
  RefreshRight,
  HomeFilled,
} from "@element-plus/icons-vue";

import {
  getHouseList,
  addHouse,
  updateHouse,
  deleteHouse,
} from "../../api/house";
import { getUserInfo } from "../../api/user";
import Drawer from "../../components/Drawer.vue";
import HouseArea from "./components/HouseArea.vue";

const loading = ref(false);
const tableData = ref([]);
const total = ref(0);
const managerOptions = ref([]);

async function loadManagerOptions() {
  try {
    const res = await getUserInfo();

    if (res.code === 0 && res.data && Array.isArray(res.data)) {
      managerOptions.value = res.data.map((user) => ({
        user_id: user.user_id,
        user_name: user.user_name || "未知用户",
        phone: user.phone || "",
      }));
    } else {
      ElMessage.error(res.msg || "获取库管人员列表失败");
      managerOptions.value = [];
    }
  } catch (error) {
    console.error("加载库管人员列表失败:", error);
    ElMessage.error("加载库管人员列表失败，请检查用户服务");
    managerOptions.value = [];
  }
}

// 搜索、分页
const queryParams = reactive({
  page: 1,
  pageSize: 10,
  name: "",
  status: null,
  type: null,
});

const houseTypeOptions = ref([
  { value: 1, label: "常温仓库" },
  { value: 2, label: "冷藏仓库" },
  { value: 3, label: "冷冻仓库" },
  { value: 4, label: "其他仓库" },
]);

// 搜索表单
const searchForm = reactive({
  name: "",
  status: null,
  type: null,
});

// 默认表单
const defaultFormData = {
  house_id: null,
  code: "",
  name: "",
  type: 1,
  condition: "",
  user_id: null,
  contact_phone: "",
  address: "",
  notes: "",
  status: 1,
};
const formData = reactive({ ...defaultFormData });
const originalFormData = reactive({ ...defaultFormData });
const formRef = ref(null);

// 表单校验
const rules = reactive({
  name: [
    { required: true, message: "仓库名称不能为空", trigger: "blur" },
    {
      min: 2,
      max: 100,
      message: "名称长度在 2 到 100 个字符之间",
      trigger: "blur",
    },
  ],
  type: [{ required: true, message: "请选择仓库类型", trigger: "change" }],
  condition: [
    { required: true, message: "存储条件不能为空", trigger: "blur" },
    { max: 50, message: "存储条件不能超过 50 个字符", trigger: "blur" },
  ],
  contact_phone: [
    { required: true, message: "联系电话不能为空", trigger: "blur" },
    {
      pattern: /^1[3-9]\d{9}$/,
      message: "请输入正确的手机号码",
      trigger: "blur",
    },
  ],
  address: [
    { required: true, message: "地址不能为空", trigger: "blur" },
    { max: 200, message: "地址长度不能超过 200 个字符", trigger: "blur" },
  ],
  user_id: [
    {
      required: true,
      message: "请选择库管人员",
      trigger: "change",
      type: "number",
    },
  ],
});

const drawer = reactive({
  visible: false,
  title: "",
  type: "add",
  id: null,
});

// 获取仓库列表
async function loadHouseList(resetPage = false) {
  if (resetPage) {
    queryParams.page = 1;
  }

  loading.value = true;
  try {
    const params = {
      page: queryParams.page,
      pageSize: queryParams.pageSize,
      name: queryParams.name,
      status: queryParams.status,
      type: queryParams.type,
    };

    const res = await getHouseList(params);

    if (res.code === 0 && res.data) {
      tableData.value = res.data.list || [];
      total.value = res.data.total || 0;

      queryParams.page = res.data.page;
      queryParams.pageSize = res.data.pageSize;
    } else {
      ElMessage.error(res.msg || "获取仓库列表失败");
      tableData.value = [];
      total.value = 0;
    }
  } catch (error) {
    console.error("获取仓库列表失败:", error);
    ElMessage.error("获取仓库列表失败，请检查网络服务");
    tableData.value = [];
    total.value = 0;
  } finally {
    loading.value = false;
  }
}

// 搜索、重置
const handleSearch = () => {
  queryParams.name = searchForm.name;
  queryParams.type = searchForm.type;
  queryParams.status = searchForm.status;
  loadHouseList(true);
};

const handleReset = () => {
  searchForm.name = "";
  searchForm.status = null;
  searchForm.type = null;
  handleSearch();
};

// 抽屉
const isFormDataSameAsOriginal = computed(() => {
  const currentData = JSON.parse(JSON.stringify(formData));
  const baseData = JSON.parse(JSON.stringify(originalFormData));

  delete currentData.code;
  delete currentData.house_id;
  delete baseData.code;
  delete baseData.house_id;

  for (const key in currentData) {
    const currentVal = String(currentData[key] ?? "");
    const baseVal = String(baseData[key] ?? "");

    if (currentVal !== baseVal) {
      return false;
    }
  }

  if (Object.keys(currentData).length !== Object.keys(baseData).length) {
    return false;
  }

  return true;
});

const openDrawer = (type, row = null) => {
  drawer.type = type; // 设置抽屉类型 (add/edit/view)

  if (type === "add") {
    Object.assign(formData, defaultFormData);
    formData.code = "保存后自动生成";
    formData.house_id = null;

    // 原始数据
    Object.assign(originalFormData, defaultFormData);
    originalFormData.code = "保存后自动生成";
  } else if (row) {
    const newFormData = {
      ...row,
      house_id: row.house_id,
      code: row.code,
      type: Number(row.type),
      condition: row.condition || "",
      user_id: row.user_id ? Number(row.user_id) : null,
      contact_phone: row.contact_phone || "",
      address: row.address || "",
      notes: row.notes || "",
      status: row.status !== undefined ? Number(row.status) : 1,
    };

    Object.assign(formData, newFormData);
    Object.assign(originalFormData, newFormData);
  }

  // 设置抽屉状态
  drawer.title =
    type === "add" ? "新增仓库" : type === "edit" ? "编辑仓库" : "查看仓库";
  drawer.id = row ? row.house_id : null;
  drawer.visible = true;

  // 打开后清空校验结果
  nextTick(() => {
    formRef.value?.clearValidate();
  });
};

// 弹窗确认
const handleCloseDrawer = (done) => {
  if (drawer.type === "view") {
    done();
    return;
  }
  if (isFormDataSameAsOriginal.value) {
    done();
    return;
  }
  ElMessageBox.confirm(
    "当前表单数据尚未保存，直接关闭将**丢失**所有更改，确定放弃修改吗?",
    "放弃修改并关闭",
    {
      confirmButtonText: "确定放弃并关闭",
      cancelButtonText: "返回编辑",
      type: "warning",
      closeOnClickModal: false,
    }
  )
    .then(() => {
      drawer.visible = false;
      done(); // 确认关闭
    })
    .catch(() => {
      // 返回编辑，取消关闭
    });
};

// 抽屉底 取消按钮
const handleCancel = () => {
  if (drawer.type === "view") {
    drawer.visible = false;
    return;
  }
  if (isFormDataSameAsOriginal.value) {
    drawer.visible = false;
    return;
  }
  ElMessageBox.confirm(
    "当前表单数据尚未保存，继续取消操作将**丢失**所有更改，确定放弃修改吗?",
    "放弃修改并关闭",
    {
      confirmButtonText: "确定放弃并关闭",
      cancelButtonText: "返回编辑",
      type: "warning",
      closeOnClickModal: false,
    }
  )
    .then(() => {
      drawer.visible = false;
    })
    .catch(() => {});
};

const handleSave = async () => {
  // 前端表单校验
  const valid = await formRef.value.validate((isValid, fields) => {
    if (!isValid) {
      console.error("表单校验失败:", fields);
    }
    return isValid;
  });
  if (!valid) {
    ElMessage.error("请检查表单输入是否正确");
    return;
  } // 保存确认
  ElMessageBox.confirm(
    `确认要${drawer.type === "add" ? "新增" : "更新"}仓库【${
      formData.name
    }】吗?`,
    "操作确认",
    {
      confirmButtonText: "确定保存",
      cancelButtonText: "取消",
      type: "info",
    }
  )
    .then(async () => {
      await executeSubmit();
    })
    .catch(() => {
      ElMessage.info("已取消保存");
    });
};

// 实际提交
const executeSubmit = async () => {
  let apiCall;
  let successMsg = "";

  const data = {
    name: formData.name,
    type: formData.type,
    condition: formData.condition,
    user_id: formData.user_id,
    contact_phone: formData.contact_phone,
    address: formData.address,
    notes: formData.notes,
    status: formData.status,
  };

  if (drawer.type === "add") {
    apiCall = addHouse(data);
    successMsg = "新增仓库成功！";
  } else if (drawer.type === "edit") {
    apiCall = updateHouse(drawer.id, data);
    successMsg = "编辑仓库成功！";
  }

  try {
    const res = await apiCall;
    if (res.code === 0) {
      ElMessage.success(res.msg || successMsg);
      drawer.visible = false;
      loadHouseList(true);
    } else {
      ElMessage.error(res.msg || "操作失败");
    }
  } catch (error) {
    console.error("提交失败:", error);
    ElMessage.error(error.message || "提交失败，请检查网络或后端服务");
  }
};

// 软删除/停用仓库
const handleDelete = (row) => {
  ElMessageBox.confirm(
    `此操作将**停用**仓库【${row.name}】及其所有区域，是否继续?`,
    "警告",
    {
      confirmButtonText: "确定停用",
      cancelButtonText: "取消",
      type: "warning",
      dangerouslyUseHTMLString: true,
    }
  )
    .then(async () => {
      try {
        const res = await deleteHouse(row.house_id);
        if (res.code === 0) {
          ElMessage.success(res.msg || "仓库已成功停用！");
          loadHouseList();
        } else {
          ElMessage.error(res.msg || "停用操作失败");
        }
      } catch (error) {
        console.error("停用失败:", error);
        ElMessage.error("停用操作失败，请检查网络或后端服务");
      }
    })
    .catch(() => {
      ElMessage.info("已取消操作");
    });
};

const handleRecover = (row) => {
  ElMessageBox.confirm(
    `确认要**恢复**仓库【${row.name}】并启用吗?`,
    "操作确认",
    {
      confirmButtonText: "确定恢复",
      cancelButtonText: "取消",
      type: "info",
      dangerouslyUseHTMLString: true,
    }
  )
    .then(async () => {
      try {
        const data = {
          name: row.name,
          type: row.type,
          condition: row.condition,
          user_id: row.user_id,
          contact_phone: row.contact_phone,
          address: row.address,
          notes: row.notes,
          status: 1,
        };
        const res = await updateHouse(row.house_id, data);
        if (res.code === 0) {
          ElMessage.success(res.msg || "仓库已成功恢复启用！");
          loadHouseList();
        } else {
          ElMessage.error(res.msg || "恢复操作失败");
        }
      } catch (error) {
        console.error("恢复失败:", error);
        ElMessage.error("恢复操作失败，请检查网络或后端服务");
      }
    })
    .catch(() => {
      ElMessage.info("已取消操作");
    });
};

// 分页事件处理
const handleSizeChange = (val) => {
  queryParams.pageSize = val;
  loadHouseList(true);
};

const handleCurrentChange = (val) => {
  queryParams.page = val;
  loadHouseList();
};

const getTypeName = (type) => {
  const option = houseTypeOptions.value.find((o) => o.value === type);
  return option ? option.label : "未知";
};

// 监听，自动填充
watch(
  () => formData.user_id,
  (newUserId) => {
    if (drawer.type === "view") {
      return;
    }
    if (newUserId) {
      const selectedUser = managerOptions.value.find(
        (user) => user.user_id === newUserId
      );

      if (selectedUser && selectedUser.phone) {
        formData.contact_phone = selectedUser.phone;

        // 清除校验
        nextTick(() => {
          formRef.value?.validateField("contact_phone");
        });
      } else if (selectedUser && !selectedUser.phone) {
        formData.contact_phone = "";
      }
    } else {
      formData.contact_phone = "";
    }
  }
);

onMounted(() => {
  loadHouseList();
  loadManagerOptions();
});
</script>
<template>
  <div class="house-container">
    <el-card class="main-card" shadow="never">
      <div class="card-header">
        <h3>
          <el-icon style="color: black"><HomeFilled /></el-icon> 仓库管理
        </h3>
        <el-button type="primary" :icon="Plus" @click="openDrawer('add')">
          新增仓库
        </el-button>
      </div>

      <el-form :inline="true" :model="searchForm" class="filter-form-inline">
        <el-row :gutter="20">
          <el-col :span="6">
            <el-form-item label="仓库名称">
              <el-input
                v-model="searchForm.name"
                placeholder="请输入仓库名称"
                clearable
              />
            </el-form-item>
          </el-col>
          <el-col :span="5">
            <el-form-item label="仓库类型">
              <el-select
                v-model="searchForm.type"
                placeholder="全部"
                clearable
                style="width: 100%"
              >
                <el-option
                  v-for="item in houseTypeOptions"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="5">
            <el-form-item label="仓库状态">
              <el-select
                v-model="searchForm.status"
                placeholder="全部"
                clearable
                style="width: 100%"
              >
                <el-option label="已启用" :value="1" />
                <el-option label="已停用" :value="0" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="6" class="action-buttons-col">
            <el-form-item>
              <el-button type="primary" :icon="Search" @click="handleSearch"
                >搜索</el-button
              >
              <el-button @click="handleReset" :icon="RefreshRight"
                >重置</el-button
              >
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>

      <el-table
        :data="tableData"
        style="width: 100%"
        v-loading="loading"
        header-cell-class-name="table-header-cell"
        row-class-name="custom-table-row"
      >
        <el-table-column type="index" label="序号" width="60" align="center" />
        <el-table-column
          prop="code"
          label="仓库编号"
          width="120"
          align="center"
        />
        <el-table-column
          prop="name"
          label="仓库名称"
          min-width="120"
          align="center"
          show-overflow-tooltip
        />
        <el-table-column
          prop="type"
          label="仓库类型"
          width="120"
          align="center"
        >
          <template #default="scope">
            {{ getTypeName(scope.row.type) }}
          </template>
        </el-table-column>
        <el-table-column
          prop="condition"
          label="存储条件"
          width="120"
          align="center"
          show-overflow-tooltip
        >
          <template #default="scope">
            {{ scope.row.condition || "未知" }}
          </template>
        </el-table-column>
        <el-table-column
          prop="user_name"
          label="负责人"
          width="120"
          align="center"
        >
          <template #default="scope">
            {{ scope.row.manager_name || "未指定" }}
          </template>
        </el-table-column>
        <el-table-column
          prop="contact_phone"
          label="联系电话"
          width="120"
          align="center"
        />
        <el-table-column prop="status" label="状态" width="120" align="center">
          <template #default="scope">
            <el-tag
              :type="scope.row.status === 1 ? 'success' : 'danger'"
              disable-transitions
            >
              {{ scope.row.status === 1 ? "启用" : "停用" }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="220" fixed="right" align="center">
          <template #default="scope">
            <el-button
              link
              type="primary"
              :icon="Edit"
              size="default"
              @click="openDrawer('edit', scope.row)"
              >编辑</el-button
            >
            <el-button
              link
              type="info"
              :icon="View"
              size="default"
              @click="openDrawer('view', scope.row)"
              >查看</el-button
            >
            <template v-if="scope.row.status === 1">
              <el-button
                link
                type="danger"
                :icon="Delete"
                size="default"
                @click="handleDelete(scope.row)"
                >停用</el-button
              >
            </template>
            <template v-else-if="scope.row.status === 0">
              <el-button
                link
                type="success"
                :icon="RefreshRight"
                size="default"
                @click="handleRecover(scope.row)"
                >恢复</el-button
              >
            </template>
          </template>
        </el-table-column>
      </el-table>

      <div class="pagination-container pagination-split">
        <span class="pagination-info">
          共 {{ total }} 条记录，第 {{ queryParams.page }}/{{
            Math.ceil(total / queryParams.pageSize)
          }}
          页
        </span>
        <el-pagination
          v-model:current-page="queryParams.page"
          v-model:page-size="queryParams.pageSize"
          :page-sizes="[10, 20, 30, 50]"
          :small="false"
          :disabled="loading"
          :background="true"
          layout=" prev, pager, next, sizes,jumper"
          :total="total"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>

    <Drawer
      v-model="drawer.visible"
      :title="drawer.title"
      :type="drawer.type"
      :size="700"
      @save="handleSave"
      @cancel="handleCancel"
      @close-request="handleCloseDrawer"
    >
      <template #default>
        <el-form
          :model="formData"
          :rules="rules"
          ref="formRef"
          label-width="100px"
          label-position="right"
          :disabled="drawer.type === 'view'"
        >
          <h4 class="form-section-title section-padding-bottom">基本信息</h4>
          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="仓库编号" prop="code">
                <el-input
                  v-model="formData.code"
                  placeholder="保存后自动生成"
                  :disabled="true"
                />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="仓库名称" prop="name" required>
                <el-input
                  v-model="formData.name"
                  placeholder="请输入仓库名称"
                />
              </el-form-item>
            </el-col>
          </el-row>

          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="仓库类型" prop="type" required>
                <el-select
                  v-model="formData.type"
                  placeholder="请选择类型"
                  style="width: 100%"
                >
                  <el-option
                    v-for="item in houseTypeOptions"
                    :key="item.value"
                    :label="item.label"
                    :value="item.value"
                  />
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="存储条件" prop="condition" required>
                <el-input
                  v-model="formData.condition"
                  placeholder="请输入存储条件（如：常温、隔离等）"
                  style="width: 100%"
                />
              </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="20">
            <el-col :span="24">
              <el-form-item label="地址" prop="address" required>
                <el-input
                  v-model="formData.address"
                  placeholder="请输入仓库详细地址"
                />
              </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="库管人员" prop="user_id" required>
                <el-select
                  v-model="formData.user_id"
                  placeholder="请选择库管人员"
                  style="width: 100%"
                  clearable
                  filterable
                  >         
                  <el-option
                    v-for="item in managerOptions"
                    :key="item.user_id"
                    :label="item.user_name"
                    :value="item.user_id"
                  >
                    <span style="float: left">{{ item.user_name }}</span>
                    <span
                      style="
                        float: right;
                        color: var(--el-text-color-secondary);
                        font-size: 13px;
                      "
                      >{{ item.phone || "无电话" }}</span
                    >
                  </el-option>
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="联系电话" prop="contact_phone" required>
                <el-input
                  v-model="formData.contact_phone"
                  placeholder="请输入联系电话"
                  :disabled="drawer.type === 'view' || !!formData.user_id"
                />
              </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="状态" prop="status">
                <el-switch
                  v-model="formData.status"
                  :active-value="1"
                  :inactive-value="0"
                  active-text="启用"
                  inactive-text="停用"
                  :disabled="drawer.type === 'add' || drawer.type === 'view'"
                />
              </el-form-item>
            </el-col>
            <el-col :span="12"> </el-col>
          </el-row>

          <h4 class="form-section-title section-padding-bottom">其他</h4>
          <el-row :gutter="20">
            <el-col :span="24">
              <el-form-item label="备注" prop="notes">
                <el-input
                  v-model="formData.notes"
                  type="textarea"
                  :rows="3"
                  placeholder="请输入备注信息"
                />
              </el-form-item>
            </el-col>
          </el-row>
        </el-form>
        <HouseArea
          :house-id="formData.house_id"
          :show="drawer.type !== 'add'"
          :parent-type="drawer.type"
        />
      </template>

      <template #footer>
        <div style="flex: auto">
          <el-button @click="handleCancel">取消</el-button>
          <el-button
            v-if="drawer.type !== 'view'"
            type="primary"
            @click="handleSave"
            >保存</el-button
          >
        </div>
      </template>
    </Drawer>
  </div>
</template>

<style scoped lang="less">
.house-container {
  min-height: 100%;
  display: flex;
  flex-direction: column;
}

.main-card {
  background: #ffffff;
  border-radius: 8px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
  margin-bottom: 18px;
  box-sizing: border-box;
  overflow: hidden;

  :deep(.el-card__body) {
    padding: 0px 15px 15px 15px;
  }
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
  border-bottom: 1px solid #d9d9d9;

  h3 {
    display: flex;
    align-items: center;
    font-size: 18px;
    font-weight: 600;
    color: #262626;

    .el-icon {
      margin-right: 8px;
      font-size: 18px;
      color: #1b82f1;
    }
  }
}

.filter-form-inline {
  :deep(.el-form-item__label) {
    width: 80px;
    text-align: right;
  }
  :deep(.el-row:last-child .el-col) {
    margin-bottom: 0;
  }

  .el-form-item {
    margin-right: 0;
    width: 100%;
  }

  .action-buttons-col {
    display: flex;
    align-items: flex-start;
    padding-bottom: 0;

    .el-form-item {
      margin-bottom: 0;
    }

    .el-button {
      margin-left: 10px;

      &:first-child {
        margin-left: 0;
      }
    }
  }
}

:deep(.el-table) {
  .el-table__row {
    // height: 40px;
    .cell {
      line-height: 25px;
    }
  }

  .el-table__header-wrapper th {
    height: 50px;
    color: black;
    background: rgba(247, 247, 247, 0.9);
    font-size: 14px;
    font-weight: 600;
    border-bottom: 1px solid rgb(235, 238, 245);
  }

  .el-table__row:hover > td {
    background-color: rgba(247, 247, 247, 0.9);
  }
}

.pagination-split {
  margin-top: 18px;
  flex-shrink: 0;
  display: flex;
  justify-content: space-between;
  align-items: center;

  .pagination-info {
    color: #595959;
    font-size: 14px;
    line-height: 28px;
  }

  :deep(.el-pagination) {
    flex: 1;
    display: flex;
    justify-content: center;
    align-items: center;
    gap: 8px;

    .el-pagination__total {
      display: none;
    }

    .el-pagination__sizes,
    .el-pagination__jump {
      display: inline-flex;
      align-items: center;
      margin-left: 10px;
      .el-input__inner {
        height: 30px;
        line-height: 30px;
        min-width: 30px;
        border-radius: 6px;
      }
    }

    .btn-prev,
    .btn-next,
    .el-pager li {
      background: white;
      border: 1px solid rgb(217, 217, 217);
      border-radius: 6px;
      color: rgb(38, 38, 38);
      min-width: 30px;
      height: 30px;
      line-height: 30px;
      padding: 0 10px;
      margin-right: 1px;
    }

    .el-pager li.is-active {
      background: rgb(27, 130, 241);
      border-color: rgb(27, 130, 241);
      color: white;
    }
  }
}

:deep(.el-drawer__body) {
  padding: 0 25px 20px 25px;
}

.form-section-title {
  font-size: 16px;
  font-weight: 600;
  color: #262626;
  margin: 0;
  padding-bottom: 8px;
  border-bottom: 1px solid rgb(217, 217, 217);
}

.section-padding-bottom {
  margin-bottom: 20px;
}
</style>
